package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@SuppressWarnings("ALL")
/**
 * @Description :
 * @author     :LD
 */
@Service
@Transactional
public class SpecGroupServiceIMpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {
    @Autowired
    private SpecParamService specParamService;

    @Override
    public List<SpecGroupDTO> querySpecList(Long categoryId) {
        //根据分类id查询规格组信息
        List<SpecGroupDTO> groups = SpecGroupDTO.convertEntityList(query().eq("category_id", categoryId).list());
        if (CollectionUtils.isEmpty(groups)){
            throw new LyException(404,"该分类下没有规格组信息");
        }
        //根据分类id查询规格参数
        List<SpecParamDTO> paramDTOS = SpecParamDTO.convertEntityList(specParamService.queryParams(categoryId, null, null));
        //将参分组并放入规格组中
        Map<Long, List<SpecParamDTO>> map = paramDTOS.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        for (SpecGroupDTO group : groups) {
            group.setParams(map.get(group.getId()));
        }
        return groups;
    }
}
